package com.ohs.ohsoa.utils;

import java.util.Date;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.auth0.jwt.JWT;
import com.ohs.ohsoa.system.entity.UserInfo;
import com.ohs.ohsoa.system.service.UserInfoService;
import com.ohs.ohsoa.system.vo.UserInfoVo;
import com.ohs.ohsoa.utils.auth.TokenService;
import com.ohs.ohsoa.utils.bean.responseBean.ResultBean;

@Aspect
@Component
public class ControllerAspect {

	@Resource
	private TokenService tokenService;

	@Resource
	private UserInfoService userInfoService;

	@Pointcut("execution(* com.ohs.ohsoa.system.controller.*.*(..))")
	public void setToken() {
	}

	@AfterReturning(value = "setToken()", returning = "data")
	public ResultBean<?> setToken(JoinPoint joinPoint, Object data) {
		ResultBean<?> r = (ResultBean<?>) data;
		
		if(checkToken()) {
		
		if (r != null) {
			UserInfoVo userInfoVo = userInfoService.getUserInfo();
			if (userInfoVo != null) {
				UserInfo userInfo = new UserInfo();
				userInfo.setUserinfoGuid(userInfoVo.getUserinfoGuid());
				userInfo.setPwd(userInfoVo.getPwd());
				String tokenNew = tokenService.getToken(userInfo);
				r.setToken(tokenNew);
			}
		}}
		return r;
	}
	
	private static boolean checkToken() {

		String token = getRequest().getHeader("token");// 从 http 请求头中取出 token
		
		try {
			Date c= JWT.decode(token).getExpiresAt();
			Date now = new Date();
			int days = (int)(c.getTime() - now.getTime())/(1000*3600*24);
			
			if(days <=3) {
				return true;
			}
		}
		catch(Exception e) {
			
		}
		return false;
	}
	
    /**
     * 获取request
     *
     * @return  requestAttributes.getRequest()
     */
    private static HttpServletRequest getRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest();
    }
}
